package com.jawmask.android.stuartproair.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jawmask.android.stuartproair.R;
import com.jawmask.android.stuartproair.constants.AppConstants;
import com.jawmask.android.stuartproair.constants.UIUtils;

public class SchedulerActivity extends BaseActivity {

	private TextView firstChoiceDateText, firstChoiceAMPM, secondChoiceDateText, secondChoiceAMPM, appointmentType, equipmentType;
	private EditText name, address, phoneNumber;

	private Date firstChoiceDate, secondChoiceDate;

	private SimpleDateFormat simpleDateFormat;

	protected static final double TOAST_HEIGHT_RATIO = 0.17;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.schedule_appointment, true);
		setTitle(getString(R.string.schedule_request));

		Date now = new Date();
		simpleDateFormat = new SimpleDateFormat(getString(R.string.date_format));

		firstChoiceDate = now;
		secondChoiceDate = now;

		firstChoiceDateText = (TextView) findViewById(R.id.firstChoiceInputDate);
		firstChoiceDateText.setText(simpleDateFormat.format(now));

		firstChoiceAMPM = (TextView) findViewById(R.id.firstChoiceAMPMInputDate);
		secondChoiceDateText = (TextView) findViewById(R.id.secondChoiceInputDate);
		secondChoiceDateText.setText(simpleDateFormat.format(now));

		secondChoiceAMPM = (TextView) findViewById(R.id.secondChoiceAMPMInputDate);
		appointmentType = (TextView) findViewById(R.id.appointmentType);
		equipmentType = (TextView) findViewById(R.id.equipmentType);

		name = (EditText) findViewById(R.id.nameInput);
		address = (EditText) findViewById(R.id.addressInput);
		phoneNumber = (EditText) findViewById(R.id.phoneNumberInput);
	}

	public void schedulerActionOnClick(final View view) {
		switch (view.getId()) {
		case R.id.firstChoiceLayoutDate:
		case R.id.firstChoiceInputDate:
			launchDateChooseDialog(firstChoiceDateText);
			break;
		case R.id.secondChoiceLayoutDate:
		case R.id.secondChoiceInputDate:
			launchDateChooseDialog(secondChoiceDateText);
			break;
		case R.id.firstChoiceAMPMLayoutDate:
		case R.id.firstChoiceAMPMInputDate:
			chooseAMPM(firstChoiceAMPM);
			break;
		case R.id.secondChoiceAMPMLayoutDate:
		case R.id.secondChoiceAMPMInputDate:
			chooseAMPM(secondChoiceAMPM);
			break;
		case R.id.appointmentTypeLayout:
		case R.id.appointmentType:
			launchAppointmentTypeActivity();
			break;
		case R.id.equipmentTypeLayout:
		case R.id.equipmentType:
			launchEquipmentTypeActivity();
			break;
		}
	}

	public void submitScheduleOnClick(final View view) {
		sendSchedule();
	}

	private void launchDateChooseDialog(final TextView tagetView) {
		int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		int month = Calendar.getInstance().get(Calendar.MONTH);
		int year = Calendar.getInstance().get(Calendar.YEAR);

		Dialog dialog = new DatePickerDialog(this, new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				if (tagetView == firstChoiceDateText)
					firstChoiceDate = new Date(year - 1900, monthOfYear, dayOfMonth);
				else if (tagetView == secondChoiceDateText)
					secondChoiceDate = new Date(year - 1900, monthOfYear, dayOfMonth);
				tagetView.setText(simpleDateFormat.format(new Date(year - 1900, monthOfYear, dayOfMonth)));
			}
		}, year, month, day);

		dialog.show();
	}

	private void chooseAMPM(final TextView tagetView) {
		String am = getString(R.string.am);
		String pm = getString(R.string.pm);

		if (tagetView.getText().equals(am)) {
			tagetView.setText(pm);
		} else if (tagetView.getText().equals(pm)) {
			tagetView.setText(am);
		}
	}

	private void launchAppointmentTypeActivity() {
		Intent intent = new Intent(this, AppointmentTypeActivity.class);
		startActivityForResult(intent, AppConstants.APPOINTMENT_TYPE_RESULT_CODE);
	}

	private void launchEquipmentTypeActivity() {
		Intent intent = new Intent(this, EquipmentTypeActivity.class);
		startActivityForResult(intent, AppConstants.EQUIPMENT_TYPE_RESULT_CODE);
	}

	private void sendSchedule() {
		List<String> errorMessage = validate();
		if (errorMessage.isEmpty()) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(getString(R.string.schedule_email_date_format));

			String firstChoice = simpleDateFormat.format(firstChoiceDate);
			String firstChoiceTimeZone = firstChoiceAMPM.getText().toString();

			String secondChoice = simpleDateFormat.format(secondChoiceDate);
			String secondChoiceTimeZone = secondChoiceAMPM.getText().toString();

			String selectedAppointmentType = appointmentType.getText().toString();
			String selectedEquipmentType = equipmentType.getText().toString();

			String customerName = name.getText().toString();
			String customerAddress = address.getText().toString();
			String customerPhoneNumber = phoneNumber.getText().toString();

			String emailSubject = getString(R.string.schedule_email_subject, customerName);
			String emailBody = getString(R.string.schedule_email_body_format, customerName, customerAddress, customerPhoneNumber, firstChoice,
					firstChoiceTimeZone, secondChoice, secondChoiceTimeZone, selectedAppointmentType, selectedEquipmentType);

			UIUtils.getInstance().launchEmailClient(this, getString(R.string.contact_email), emailSubject, emailBody,
					getString(R.string.schedule_request));
		} else {
			showErrorMessage(errorMessage);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			String selectedItemName = data.getStringExtra(AppConstants.EXTRA_KEY_NAME_SELECTED_RESULT);
			if (requestCode == AppConstants.APPOINTMENT_TYPE_RESULT_CODE) {
				appointmentType.setText(selectedItemName);
			} else if (requestCode == AppConstants.EQUIPMENT_TYPE_RESULT_CODE) {
				equipmentType.setText(selectedItemName);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private List<String> validate() {
		List<String> errorMessage = new ArrayList<String>();

		if (appointmentType.getText().toString().equals(getString(R.string.appointment_type_smart))) {
			errorMessage.add(getString(R.string.required_appointment_type));
		} else if (equipmentType.getText().toString().equals(getString(R.string.equipment_type_smart))) {
			errorMessage.add(getString(R.string.required_equipment_type));
		} else if (name.length() == 0) {
			errorMessage.add(getString(R.string.required_name));
		} else if (address.length() == 0) {
			errorMessage.add(getString(R.string.required_address));
		} else if (phoneNumber.length() == 0) {
			errorMessage.add(getString(R.string.required_phone_number));
		}

		return errorMessage;
	}

	private void showErrorMessage(final List<String> errorMessageList) {
		StringBuffer errorMessage = new StringBuffer();

		for (String error : errorMessageList) {
			errorMessage.append(getString(R.string.error_msg_format, error));
			errorMessage.append("\n");
		}

		Toast toast = Toast.makeText(this, errorMessage.toString(), Toast.LENGTH_LONG);
		toast.setGravity(Gravity.TOP, 0, (int) (getMeasuredHeight() * TOAST_HEIGHT_RATIO));
		toast.show();
	}

	protected int getMeasuredHeight() {
		WindowManager w = getWindowManager();
		Display d = w.getDefaultDisplay();
		return d.getHeight();
	}
}